
<script setup>
	
	import port from './lib/port';
	import store from './lib/store';
	import { onShow } from "@dcloudio/uni-app";
	import useCountdown from './hook/useCountdown';
	import { computed, ref, reactive } from 'vue';
	import useWordMarker from './hook/useWordMarker';
	import c_markitem from './components/markitem.vue';

	
	/** 词汇相关共享数据 */
	const storeData = store();
	
	/** 计时器 */
	const countdown = useCountdown();
	
	/** 单词标记 */
	const wordMarker = useWordMarker();
	
	/** 分组列表 */
	const groupList = ref([]);
	
	/** 分组索引 */
	const groupIndex = ref(0);

	/** 当前标识 */
	const state = reactive({
		selectedItem: null,
		markedItem: { 
			groupIndex: null, 
			childIndex: null
		}
	});

	
	/** 标记规则 */
	const moves = ref([1, 0, 1, 2, 1, 0, 1, 2, 3, 2, 1, 0, 1, 2, 3, 4, 3, 2, 3, 4, 1, 0, 1, 0, 1, 2, 3, 4, 3, 2, 1, 0]);
	
	/** 标记位置 */
	const currentMoveIndex = ref(0);
	

	/** 分组 */
	function groupedArray() {
		groupList.value = [];
		currentMoveIndex.value = 0;
		const templist = storeData.selectWordlist;
		const chunkSize = 5;
		for (let i = 0; i < templist.length; i += chunkSize) {
			const _templist = templist.slice(i, i + chunkSize).map((item, index) => {
				/** 标记单词 */
				item.word = wordMarker.markers(item.marks, item.word, index);
				return item;
			});
			
			groupList.value.push(_templist);
		};
		
		switch(true) {
			case groupList.value[groupIndex.value].length === 3: {
				moves.value = [1, 0, 1, 2, 1, 0, 1, 2];
				break;
			}
			
			case groupList.value[groupIndex.value].length === 4: {
				moves.value = [1, 0, 1, 2, 1, 0, 1, 2, 3, 2, 1, 0, 1, 2, 3];
				break;
			}
			
			case groupList.value[groupIndex.value].length <= 2: {
				currentMoveIndex.value = -1;
				break;
			}
		};
		
		state.markedItem = { 
			groupIndex: groupIndex.value, 
			childIndex: moves.value[currentMoveIndex.value] 
		};
	};
	
	/** 初始化一次 */
	groupedArray();

	/** 剪子盒状态 */
	const ispaperStatus = computed(() => {
		let count = 0;
		groupList.value.length && groupList.value[groupIndex.value].forEach((item) => {
			if(item.isclick) count++;
		});
		
		return count === groupList.value[groupIndex.value].length;
	});


	/** 是否选中 */
	const isActive = (groupIndex, childIndex) => {
		return state.selectedItem && state.selectedItem.groupIndex === groupIndex && state.selectedItem.childIndex === childIndex;
	};

	/** 是否标记 */
	const isMarked = (groupIndex, childIndex) => {
	  return state.markedItem.groupIndex === groupIndex && state.markedItem.childIndex === childIndex;
	};


	/** 上一次播放的位置 */
	const playlastIndex = ref([0, 0]);

	/** 记录点击次数 */
	const setClick = (index = playlastIndex.value[0], keys = playlastIndex.value[1]) => {
		groupList.value[index][keys].clickCount = groupList.value[index][keys].clickCount ? ++groupList.value[index][keys].clickCount : 1;
	};

	/** 点击 */
	const handleClick = (index, keys, toast = true) => {
		if (index === playlastIndex.value[0] && keys === playlastIndex.value[1]) {
			setClick();
			return true;
		};
		
		if (groupList.value[playlastIndex.value[0]][playlastIndex.value[1]].clickCount < 3) {
			toast && uni.showToast({ icon: 'none', title: '上一个词汇还未学习三次~' });
			return false;
		};
		
		setClick(index, keys);
		return true;
	};

	/** 播放结束 */
	const playEnd = () => {
		groupList.value[playlastIndex.value[0]][playlastIndex.value[1]].play = false;
	};

	/** 监听自然结束 */
	uni.useAudio.onEnded(playEnd);

	/** 监听播放暂停 */
	uni.useAudio.onStop(playEnd);
	
	
	/** 记录点击第几项 */
	const kidxs = ref(0);

	/** 播放词汇 */
	const playEvent = (data, index, keys) => {
		playEnd();
		if(kidxs.value != keys) data.clickMarkitemCount = 0;
		data.clickMarkitemCount = data.clickMarkitemCount ? ++data.clickMarkitemCount : 1;
		if (data.clickMarkitemCount === 4) data.clickMarkitemCount = 1;
		playlastIndex.value = [index, keys];
		data.play = true;
		data.isclick = true;
		uni.useAudio.src(data.voiceFile?.url);
		
		if (!data.playWord) {
			/** 首次点击 */
			data.playWord = true;
			data.blockTranslation = false;
			
		} else if (data.clickMarkitemCount > 1) {
			/** 二次点击 */
			data.playWord = false;
			data.blockTranslation = true;
		};
		
		clickItemEvent(index, keys);
		kidxs.value = keys;
	};

	/** 点击辅助函数 */
	function clickItemEvent(groupIndex, childIndex){
		state.selectedItem = { groupIndex, childIndex };
		if (moves.value.length <= 2) return;
		else {
			if (childIndex === moves.value[currentMoveIndex.value]) {
				currentMoveIndex.value++
				state.markedItem = { groupIndex: groupIndex, childIndex: moves.value[currentMoveIndex.value] };
			};
		};
	};

	/** 去剪子盒 */
	function goPaperEvent(){
		playEnd();
		groupList.value.map(child => {
			child.map((item, index) => {
				/** 清除单词标记 */
				item.word = wordMarker.clearMark(item.marks, item.word, index);
				delete item.play;
				delete item.isclick;
				delete item.playWord;
				delete item.blockTranslation;
			});
		});
		
		/** 设置剪子盒数据 */
		storeData.setShearsBox({
			list: groupList.value,
			index: groupIndex.value
		});
		
		uni.redirectTo({
			url: '/pages/course/word/paper'
		});
	};

	function nextEvent(index) {
		playlastIndex.value = [index, 0];
		groupIndex.value = +index;
		groupedArray();
		
		/** 设置下一组索引 */
		storeData.setShearsBox('nextIndex', 0);
	};

	/** 洗牌数组 */
	function shuffleArray(){
		playEnd();
		const currentIndex = groupIndex.value;
		const array = groupList.value[currentIndex];
		let i = array.length, temporaryValue, randomIndex;
		while (0 !== i) {
			randomIndex = Math.floor(Math.random() * i);
			i -= 1;
			temporaryValue = array[i];
			array[i] = array[randomIndex];
			array[randomIndex] = temporaryValue;
		};
		
		groupList.value[currentIndex] = array;
	};

	/** 顺序播放索引 */
	const shunxuIndex = ref(0);
	
	/** 顺序播放方法 */
	async function shunxuplay(){
		playEnd();
		const startIndex = playlastIndex.value[0];
		let endIndex = groupList.value[startIndex][playlastIndex.value[1]].clickCount < 3 || !groupList.value[startIndex][playlastIndex.value[1]].clickCount ? playlastIndex.value[1] : playlastIndex.value[1] + 1;
		endIndex = endIndex > groupList.value[startIndex].length - 1 ? 0 : endIndex;
		const bool = handleClick(startIndex, endIndex, false);
		bool && playEvent(groupList.value[startIndex][endIndex], startIndex, endIndex);
	};


	/** 暴露方法 */
	defineExpose({
		handleClick
	});
	
	
	/** 删除标记 */
	const deleteSign = (item, index) => {
		/** 清除单词标记 */
		item.word = wordMarker.clearMark(item.marks, item.word, index);
		delete item.play;
		delete item.isclick;
		delete item.playWord;
		delete item.blockTranslation;
		return item;
	};
	
	
	/** 进入页码时 */
	onShow(() => {
		storeData.shearsBox.nextIndex && nextEvent(storeData.shearsBox.nextIndex);
		countdown.start(() => {
			const words = []
			if (groupIndex.value != groupList.value.length) {
				groupList.value.forEach((item, ele) => ele <= groupIndex.value - 1 && item.forEach((item1, ele1) => words.push(deleteSign(item1, ele1))));
				
			} else {
				groupList.value.forEach((item, ele) => item.forEach((item1, ele1) => words.push(deleteSign(item1, ele1))));
			};
			
			/** 设置最小分组 */
			storeData.setShearsBox('mixGroup', 0);
			
			/** 设置学习后的列表 */
			storeData.setlist('afterStudylist', words);
			uni.redirectTo({
				url: '/pages/course/word/after'
			});
		});
	});


</script>

<template>
	<view class="containerbox">
		<uv-navbar title="单词标记" left-icon="" placeholder bg-color="#4d6d8a" title-style="color:#fff"/>
		
		<template v-for="item,index in groupList" :key="index">
			<scroll-view class="containerbox px-30" v-if="groupIndex === index">
				<view v-for="child,keys in item" :key="child.id">
					<c_markitem
						:item="child" 
						:index="keys" 
						:ischeck="false"
						:item-index="index"
						:mark="isMarked(index, keys)"
						:selected="isActive(index, keys)"
						@play="playEvent(child, index, keys)"
					/>
				</view>
			</scroll-view>
		</template>
		
		<view class="flex items-center justify-between bottombox">
			<view class="flex-1">
				<view class="text-26 text-white">
					<text class="text-32 mx-5 color-ff5252">{{ groupIndex + 1 }}</text>
					/
					<text class="text-32 text-white mx-5">{{ groupList.length }}</text>
				</view>
			</view>
			
			<view class="btn bgc-warning" v-if="ispaperStatus" @click="goPaperEvent">剪纸盒</view>
			<view class="btn bgc-warning" @click="shuffleArray">随机</view>
		</view>
		
		<audio />
	</view>
</template>


<style lang="scss" scoped>
	@import "./style/common.scss";
</style>